package com.universal.frame.generalutils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.squareup.picasso.Picasso;
import com.universal.frame.views.LoadingView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * RoreyDiu
 * 2016-04-11整体调整
 * <p>
 * 普通常用工具类
 */
public class GeneralUtil {

    /**
     * 比较两个对象是否相等
     *
     * @param actual
     * @param expected
     * @return <ul>
     * <li>if both are null, return true</li>
     * <li>return actual.{@link Object#equals(Object)}</li>
     * </ul>
     */
    public static boolean isEquals(Object actual, Object expected) {
        return actual == expected
                || (actual == null ? expected == null : actual.equals(expected));
    }

    /**
     * 将dp类型的尺寸转换成px类型的尺寸
     *
     * @param size
     * @param context
     * @return
     */
    public static int DPtoPX(int size, Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
        return (int) ((float) size * metrics.density + 0.5);
    }

    /**
     * 压缩图片
     */
    public static Bitmap scaleImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 设置想要的大小
        int newWidth1 = newWidth;
        int newHeight1 = newHeight;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth1) / width;
        float scaleHeight = ((float) newHeight1) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(0);

        return Bitmap.createScaledBitmap(bm, newWidth, newHeight, false);
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(Activity activity) {
        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(activity
                .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 验证身份证号码
     */
    public static boolean validateIdCard(String idCard) {
        if (StringUtil.isNull(idCard))
            return false;
        String pattern = "^[0-9]{17}[0-9|xX]{1}$";
        return idCard.matches(pattern);
    }

    /**
     * bitmap转为base64
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encode(bitmapBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取富文本内容
     */
    public static String getHtml(String content) {
        String html = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"
                + "<style type=\"text/css\">body { font-family: Arial,\"microsoft yahei\",Verdana; padding:0;	margin:0; font-size:14px; color:#565656; background: #fff; overflow-x:hidden; }img {padding:0; margin:0; vertical-align:top; border: none}li,ul {list-style: none outside none; padding: 0; margin: 0}input[type=text],select {-webkit-appearance:none; -moz-appearance: none; margin:0; padding:0; background:none; border:none; font-size:14px; text-indent:3px; font-family: Arial,\"microsoft yahei\",Verdana;}.wrapper { width:100%; padding:10px; box-sizing:border-box;}p { color:#666; line-height:1.6em;}.wrapper img { display:block; max-width:100%; height:auto !important; margin-bottom:10px;} p { margin-bottom:10px;}</style>"
                + "</head><body><div class=\"wrapper\">" + content + "</div></body></html>";
        return html;
    }


    /**
     * 获取手机屏幕的参数
     **/
    public static void getWindowAttrribute(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int windowWidth = metric.widthPixels;// 屏幕宽度（像素）
        int windowHeight = metric.heightPixels;// 屏幕高度（像素）
        float windowDensity = metric.density;// 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;// 屏幕密度DPI（120 / 160 / 240）
        SharedPreferencesUtil.putInt(activity, "windowWidth", windowWidth);
        SharedPreferencesUtil.putInt(activity, "windowHeight", windowHeight);
        SharedPreferencesUtil
                .putFloat(activity, "windowDensity", windowDensity);
    }

    /**
     * Picasso加载图片
     * @param context 上下文
     * @param imageView 图片控件
     * @param url 图片URL
     * @param placeholder 默认图片
     * @param error 图片加载失败显示图片
     */
    public static void loadingNetImg(Context context, ImageView imageView, String url, int placeholder, int error) {

        if (context == null) {
            imageView.setImageResource(placeholder);
            return;
        }

        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(placeholder);
            return;
        }
        //		if(!url.contains(HttpAddress.IMG_SERVICE_URL)){
        //			url = HttpAddress.IMG_SERVICE_URL + url;
        //		}
        try {
            Picasso.with(context).load(url).placeholder(placeholder).error(error).into(imageView);
        } catch (OutOfMemoryError e) {
            Picasso.with(context).load(placeholder).into(imageView);
        } catch (Exception e) {
            Picasso.with(context).load(placeholder).into(imageView);
        }

    }


    /**
     * //透明状态栏
     * getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
     * //透明导航栏
     * getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public static String asteriskString(String str) {
        String regex = "(\\w{1})(.*)(\\w{1})";
        Matcher m = Pattern.compile(regex).matcher(str);
        if (m.find()) {
            String rep = m.group(2);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rep.length(); i++) {
                if (i < 3) {
                    sb.append("*");
                }
            }
            return str.replaceAll(rep, sb.toString());
        } else {
            return str;
        }
    }


    /**
     * 格式化字串
     *
     * @param str
     * @return str 返回保留两位数的字串
     */
    public static String formatDouble(String str) {
        try {
            if (!TextUtils.isEmpty(str)) {
                double parseDouble = Double.parseDouble(str);
                /*DecimalFormat df = new DecimalFormat("0.00");
                return df.format(parseDouble);*/
                // 想要转换成指定国家的货币格式
                NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CHINA);
                String numString = format.format(parseDouble);
                return numString.substring(1, numString.length());
            } else {
                return "0.00";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    /**
     * 捕获异常抛出
     *
     * @param context
     * @param e
     */
    public static void tryShow(Context context, Exception e) {
        e.printStackTrace();
        ToastUtil.showToast(context, "填充数据或者解析异常");
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取当前时间
     */
    public static String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 时间比较
     */
    public static int compareTime(Context context, String s1, String s2) {
        java.text.DateFormat df = new SimpleDateFormat("HH:mm:ss");
        java.util.Calendar c1 = java.util.Calendar.getInstance();
        java.util.Calendar c2 = java.util.Calendar.getInstance();
        try {
            c1.setTime(df.parse(s1));
            c2.setTime(df.parse(s2));
        } catch (java.text.ParseException e) {
            ToastUtil.showToast(context, "格式不正确");
        }
        int result = c1.compareTo(c2);
        //		if(result==0)
        //			System.out.println("c1相等c2");
        //		else if(result<0)
        //			System.out.println("c1小于c2");
        //		else
        //			System.out.println("c1大于c2");
        return result;
    }

    public static void setImageViewHeight(ImageView mImageView) {
        LinearLayout.LayoutParams mLayoutParams = (LinearLayout.LayoutParams) mImageView.getLayoutParams();
        mLayoutParams.height = mLayoutParams.width / 2;
        mImageView.setLayoutParams(mLayoutParams);
    }

    /***
     * 请求网络出错，显示错误页面
     *
     * @param context
     * @param loadingView
     * @param contentView
     */
    public static void showNetErrorView(Context context, LoadingView loadingView, View contentView) {
        if (null != loadingView && null != contentView) {
            loadingView.setVisibility(View.VISIBLE);
            loadingView.showNoNetwrokView();
            contentView.setVisibility(View.GONE);
        }

    }

    public static void showNetErrorView(Context context, View contentView) {
        if (null != contentView) {
            contentView.setVisibility(View.GONE);
        }

    }

    public static long str2Long(String str, long defValue) {

        if (TextUtils.isEmpty(str)) {
            return defValue;
        }

        try {

            return Long.valueOf(str);

        } catch (Exception e) {

            return defValue;
        }

    }

    /***
     * 获取APK存放路径
     *
     * @param context
     * @param version
     * @return
     */
    public static String getAPKSaveFilePath(Context context, String version) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在

//		String fileName = "lanyaoo_android"
//				+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
//				+ ".apk";

        if (version.contains(".")) {
            version = version.replace(".", "");
        }


        String fileName = "Io_android_v" + version + ".apk";

        if (sdCardExist) {
            return Environment.getExternalStorageDirectory().toString()
                    + File.separator + "Io" + File.separator + fileName;
        } else {
            return context.getCacheDir().getAbsolutePath() + fileName;
        }
    }

    /*判断集合是否为空*/
    public static <V> boolean isEmpty(List<V> sourceList) {
        return (sourceList == null || sourceList.size() == 0);
    }


    /**
     * 格式化价格(保留小数点后两位)
     *
     * @param argStr
     * @return
     */
    public static String getFloatDotStr(String argStr) {
        float arg = Float.valueOf(argStr);
        DecimalFormat fnum = new DecimalFormat("##0.00");
        return fnum.format(arg);
    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 网络是否可用
     * @date 2015年7月15日 下午12:07:56
     */
    public static boolean IsInternetValidate(final Context context) {
        try {
            ConnectivityManager manger = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manger.getActiveNetworkInfo();
            return (info != null && info.isConnected());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @return String
     * @author 赵成龙
     * @Description 得到应用版本名
     * @date 2015年7月15日 下午12:08:15
     */
    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;

    }

    /**
     * @return int
     * @author 赵成龙
     * @Description 得到应用版本号
     * @date 2015年7月15日 下午12:08:55
     */
    public static int getVersionCode(Context context) {
        int verCode = 0;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verCode;

    }

    /**
     * @return String
     * @author 赵成龙
     * @Description 毫秒格式化
     * @date 2015年7月15日 下午12:09:46
     */
    public static String millisToString(long millis) {
        boolean negative = millis < 0;
        millis = Math.abs(millis);

        millis /= 1000;
        int sec = (int) (millis % 60);
        millis /= 60;
        int min = (int) (millis % 60);
        millis /= 60;
        int hours = (int) millis;

        String time;
        DecimalFormat format = (DecimalFormat) NumberFormat
                .getInstance(Locale.US);
        format.applyPattern("00");
        if (millis > 0) {
            time = (negative ? "-" : "")
                    + (hours == 0 ? 00 : hours < 10 ? "0" + hours : hours)
                    + ":" + (min == 0 ? 00 : min < 10 ? "0" + min : min) + ":"
                    + (sec == 0 ? 00 : sec < 10 ? "0" + sec : sec);
        } else {
            time = (negative ? "-" : "") + min + ":" + format.format(sec);
        }
        return time;
    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 判断 多个字段的值否为空
     * @date 2015年7月15日 下午12:10:13
     */
    public static boolean isNull(String... ss) {
        for (int i = 0; i < ss.length; i++) {
            if (null == ss[i] || ss[i].equals("")
                    || ss[i].equalsIgnoreCase("null")) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 判断 一个字段的值否为空
     * @date 2015年7月15日 下午12:10:30
     */
    public static boolean isNull(String s) {
        return null == s || s.equals("") || s.equalsIgnoreCase("null");

    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 判断sd卡是否存在
     * @date 2015年7月15日 下午12:11:26
     */
    public static boolean isSDCardAvailable() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 显示纯汉字的星期名称
     *
     * @param i 星期：1,2,3,4,5,6,7
     * @return
     * @author TangWei 2013-10-25上午11:31:51
     */
    public static String changeWeekToCN(int i) {
        switch (i) {
            case 1:
                return "星期一";
            case 2:
                return "星期二";
            case 3:
                return "星期三";
            case 4:
                return "星期四";
            case 5:
                return "星期五";
            case 6:
                return "星期六";
            case 7:
                return "星期日";
            default:
                return "";
        }
    }

    /**
     * 验证手机号码
     *
     * @param phone
     * @return
     * @author TangWei
     */
    public static boolean validatePhone(String phone) {
        if (isNull(phone))
            return false;
        if (phone.length() != 11) {
            return false;
        }
        String pattern = "^1[3,4,5,6,8]+\\d{9}$";
        return phone.matches(pattern);
    }

    /**
     * 简单的验证一下银行卡号
     *
     * @param bankCard 信用卡是16位，其他的是13-19位
     * @return
     */
    public static boolean validateBankCard(String bankCard) {
        if (isNull(bankCard))
            return false;
        String pattern = "^\\d{13,19}$";
        return bankCard.matches(pattern);
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     * @author TangWei 2013-12-13下午2:33:16
     */
    public static boolean validateEmail(String email) {
        if (isNull(email))
            return false;
        String pattern = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
        return email.matches(pattern);
    }

    /**
     * 隐藏系统键盘,光标依然正常显示;兼容了高低版本;
     *
     * @param editText
     */
    public static void hideSoftInputMethod(Activity activity, EditText editText) {
        activity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }
        if (methodName == null) {
            editText.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName,
                        boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);
            } catch (NoSuchMethodException e) {
                editText.setInputType(InputType.TYPE_NULL);
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将100以内的阿拉伯数字转换成中文汉字（15变成十五）
     *
     * @param round 最大值50
     * @return >99的，返回“”
     */
    public static String getHanZi1(int round) {
        if (round > 99 || round == 0) {
            return "";
        }
        int ge = round % 10;
        int shi = (round - ge) / 10;
        String value = "";
        if (shi != 0) {
            if (shi == 1) {
                value = "十";
            } else {
                value = getHanZi2(shi) + "十";
            }

        }
        value = value + getHanZi2(ge);
        return value;
    }

    /**
     * 将0-9 转换为 汉字（ _一二三四五六七八九）
     *
     * @param round
     * @return
     */
    private static String getHanZi2(int round) {
        String[] value = {"", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        return value[round];
    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 根据Unicode编码完美的判断中文汉字和符号
     * @date 2015年7月15日 下午12:12:42
     */
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
    }

    /**
     * @return boolean
     * @author 赵成龙
     * @Description 完整的判断中文汉字和符号
     * @date 2015年7月15日 下午12:12:55
     */
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!isChinese(c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取屏幕分辨率
     *
     * @param context
     * @return
     */
    @SuppressWarnings("deprecation")
    public static int[] getScreenDispaly(Context context) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();// 手机屏幕的宽度
        int height = windowManager.getDefaultDisplay().getHeight();// 手机屏幕的高度
        // 1080 1920
        // 480 854
        // 720 1280
        /** 低档 */
        if (width == 480) {
            width = width - 80;
            height = height - 80;
        } else if (width == 720) {
            /** 中档 */
            width = width - 120;
            height = height - 120;
        } else if (width == 1080) {
            /** 高档 */
            width = width - 180;
            height = height - 180;
        } else if (width == 3840) {
            /** 2k */
            width = width - 300;
            height = height - 300;
        }
        int result[] = {width, height};
        return result;
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public static void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 中间加空格的字符串
     *
     * @param
     */
    public static String appendSpace(String para) {
        int length = para.length();
        char[] value = new char[length << 1];
        for (int i = 0, j = 0; i < length; ++i, j = i << 1) {
            value[j] = para.charAt(i);
            value[1 + j] = ' ';
        }
        return new String(value);
    }

    /**
     * 返回隐藏中间数字的手机号字符串
     *
     * @param str
     * @return
     */
    public static String getPhoneString(String str) {
        if (str != null && !"".equals(str)) {
            return str.substring(0, str.length() - (str.substring(3)).length())
                    + " XXXX " + str.substring(7);
        }
        return "";
    }

    /**
     * 返回隐藏中间数字的号字符串
     *
     * @param str
     * @return
     */
    public static String getIdTypeString(String str) {
        String IdTypeStr = "";
        if (str.length() == 18) {
            IdTypeStr = str.substring(0,
                    str.length() - (str.substring(8)).length())
                    + "********" + str.substring(16);
        } else if (str.length() == 15) {
            IdTypeStr = str.substring(0,
                    str.length() - (str.substring(8)).length())
                    + "********" + str.substring(13);
        }
        return IdTypeStr;
    }

    /**
     * 格式化金额
     */
    public static String getFormatAsset(String s) {
        String b = "";
        String t = "";
        if (s.contains(".")) {
            if (Double.valueOf(s) == 0) {
                return "0";
            } else {
                int len = s.indexOf(".");
                b = s.substring(len);
                t = s.substring(0, len);
                if (t.length() > 3) {
                    StringBuffer sb = new StringBuffer();
                    char[] chars = t.toString().replace(" ", "").toCharArray();
                    if (s.length() % 3 == 0) {
                        for (int i = 0; i < chars.length; i++)
                            if (i % 3 == 0 && i != 0) {
                                sb.append(",");
                                sb.append(chars[i]);
                            } else {
                                sb.append(chars[i]);
                            }

                    } else if (t.length() % 3 == 1) {
                        for (int i = 0; i < chars.length; i++) {
                            if (i % 3 == 1 && i != 0) {
                                sb.append(",");
                                sb.append(chars[i]);
                            } else {
                                sb.append(chars[i]);
                            }
                        }
                    } else if (t.length() % 3 == 2) {
                        for (int i = 0; i < chars.length; i++) {
                            if (i % 3 == 2 && i != 0) {
                                sb.append(",");
                                sb.append(chars[i]);
                            } else {
                                sb.append(chars[i]);
                            }
                        }
                    }
                    if (b.length() == 2) {
                        sb.append(b).append("0");
                    } else {
                        sb.append(b);
                    }
                    return sb.toString();
                } else {
                    if (b.length() == 2) {
                        return s + "0";
                    } else {
                        return s;
                    }
                }
            }
        } else {
            if (s.length() > 3) {
                StringBuffer sb = new StringBuffer();
                char[] chars = s.toString().replace(" ", "").toCharArray();
                if (s.length() % 3 == 0) {
                    for (int i = 0; i < chars.length; i++)
                        if (i % 3 == 0 && i != 0) {
                            sb.append(",");
                            sb.append(chars[i]);
                        } else {
                            sb.append(chars[i]);
                        }

                } else if (s.length() % 3 == 1) {
                    for (int i = 0; i < chars.length; i++) {
                        if (i % 3 == 1 && i != 0) {
                            sb.append(",");
                            sb.append(chars[i]);
                        } else {
                            sb.append(chars[i]);
                        }
                    }
                } else if (s.length() % 3 == 2) {
                    for (int i = 0; i < chars.length; i++) {
                        if (i % 3 == 2 && i != 0) {
                            sb.append(",");
                            sb.append(chars[i]);
                        } else {
                            sb.append(chars[i]);
                        }
                    }
                }
                sb.append(".00");
                return sb.toString();
            } else if (Double.valueOf(s) == 0) {
                return "0";
            } else if (s.length() <= 3) {
                return s + "0.00";
            }
        }
        return null;
    }

    /**
     * 密码输入隐藏，没有回显效果
     */
    public static String getStars(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append("*");
        }
        return sb.toString();
    }

    /**
     * 数组降序
     *
     * @param a
     */
    public static void sort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[j] > a[i]) {
                    int t = a[j];
                    a[j] = a[i];
                    a[i] = t;
                }
            }
        }
    }


    /**
     * 输入框小数点后保留两位
     *
     * @param editText
     */
    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    static long lastClickTime;

    /**
     * 防止多次点击重复页面的问题.传递机制
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (timeD >= 0 && timeD <= 500) {
            return true;
        } else {
            lastClickTime = time;
            return false;
        }
    }

    /**
     * 判断当前应用程序处于前台还是后台(不需要额外权限)
     *
     * @param context
     * @return
     */
    public static boolean isBackground(Context context) {
        android.app.ActivityManager activityManager = (android.app.ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (android.app.ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                // Log.i("后台", appProcess.processName);
// Log.i("前台", appProcess.processName);
                return appProcess.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
            }
        }
        return false;
    }

    /**
     * 判断当前应用程序处于前台还是后台(需要额外权限)
     *
     * @param context
     * @return
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        android.app.ActivityManager am = (android.app.ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        android.app.ActivityManager activityManager = (android.app.ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 关闭软键盘
     */
    public static void OnInputWetbod(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

        }
    }

    /**
     * 判断文件是否存在-true为存在
     *
     * @param path
     * @return
     */
    public static boolean ifFileExists(String path) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }


    /**
     * @param @param  context
     * @param @return 设定文件
     * @return String 返回类型
     */
    public static String getVersionNumber(Context context) {
        String version = null;
        // 获取PackageManager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (Exception e) {
            return "版本号 : ";
        }
        return version;
    }


    public static String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        second = l.intValue();
        if (second > 60) {
            minute = second / 60;         //取整
            second = second % 60;         //取余
        }

        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        String strtime = hour + "：" + minute + "：" + second;
        return strtime;
    }

    public static String kjtoString(String args)
    {
        BigDecimal bd = new BigDecimal("1.03219E+14");
        return bd.toPlainString();
    }


}
